package com.reserveme;

import com.reserveme.Resource;
import com.reserveme.PMF;
import java.util.List;
import javax.jdo.Query;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;

import javax.jdo.PersistenceManager;


public class QueryWrapper {
  public List<Resource> query(Date dateParam, String groundParam) {
	  PersistenceManager pm = PMF.get().getPersistenceManager();
	  Query query = pm.newQuery(Resource.class);
	  
	  if(groundParam != "") {
		  query.setFilter("this.ground==groundParam && this.date==dateParam");
		  query.declareParameters("groundParam,dateParam");
		  @SuppressWarnings( "unchecked" )
		  List<Resource> results = (List<Resource>) query.execute(groundParam,dateParam);
		  return results;
	  } else {
		  query.setFilter("this.date==dateParam");
		  query.declareParameters("String dateParam");
		  @SuppressWarnings( "unchecked" )
		  List<Resource> results = (List<Resource>) query.execute(dateParam.toString());
		  return results;
	  } 
  }
  
  public void insert(String dateParam, String groundParam) throws Exception{
	  PersistenceManager pm = PMF.get().getPersistenceManager();
	  try {
		  SimpleDateFormat datef = new SimpleDateFormat();
		  datef.applyPattern("yyyy/M/d");
		  Date date = datef.parse(dateParam);
		  Resource grnd = new Resource(groundParam, date);
		  
		  pm.makePersistent(grnd);
	  } catch(ParseException e) {
		  throw new Exception("Invalid date passed: " + dateParam + "\n" + e.getMessage());
	  } finally {
		  pm.close();
	  }
	  
  }
}
